<template>
	<view class="login-form">
		<uni-forms ref="formRef" :modelValue="form" :rules="rules">
			<uni-forms-item name="phone">
				<uni-easyinput v-model="form.phone" placeholder="请输入手机号" prefixIcon="phone"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="code">
				<uni-easyinput v-model="form.code" placeholder="请输入验证码" prefixIcon="chat">
					<template v-slot:right>
						<button class="sms-btn" size="mini" :disabled="!isPhoneValid || isCounting"
							@click="handleSendSms">
							{{ btnText }}
						</button>
					</template>
				</uni-easyinput>
			</uni-forms-item>
			<button class="login-btn" type="primary" @click="handleSubmit"
				:style="{ backgroundColor: getTheme.themeColor, color: '#fff', fontSize: '14px' }">立即登录</button>
		</uni-forms>
	</view>
</template>

<script setup lang="ts">
	import { ref, reactive, computed } from "vue";
	import { useAuthStore } from "@/stores/auth";
	const authStore = useAuthStore();
	const getTheme = authStore.getTheme();

	const form = reactive({
		phone: "",
		captcha_token: "",
		type: "login",
		code: ""
	});

	const rules = reactive({
		phone: {
			rules: [
				{
					required: true,
					errorMessage: "请输入手机号"
				},
				{
					pattern: /^1[3-9]\d{9}$/,
					errorMessage: "手机号格式不正确"
				}
			]
		},
		code: {
			rules: [
				{
					required: true,
					errorMessage: "请输入验证码"
				}
			]
		}
	});

	const formRef = ref<any>(null);
	const countdown = ref(0);
	const isCounting = ref(false);
	const timer = null;

	const isPhoneValid = computed(() => {
		return /^1[3-9]\d{9}$/.test(form.phone);
	});

	const btnText = computed(() => {
		return isCounting.value ? `${countdown.value}秒后重试` : "获取验证码";
	});

	const emit = defineEmits(["submit", "send-sms"]);

	const handleSubmit = async () => {
		try {
			await formRef.value.validate();
			emit("submit", {
				phone: form.phone,
				captcha_token: form.captcha_token,
				type: form.type
			});
		} catch (err) {
			console.log("表单验证失败:", err);
		}
	};

	const handleSendSms = () => {
		if (!isPhoneValid.value) return;

		emit("send-sms", form.phone, () => {
			// 验证码发送成功后的回调
			startCountdown();
		});
	};

	const startCountdown = () => {
		isCounting.value = true;
		countdown.value = 60;
		timer = setInterval(() => {
			countdown.value--;
			if (countdown.value <= 0) {
				clearInterval(timer);
				isCounting.value = false;
			}
		}, 1000);
	};
</script>

<style lang="scss" scoped>
	.login-form {
		margin-top: 20px;
	}

	.login-btn {
		width: 100%;
		border-radius: 4px;
	}

	.sms-btn {
		margin-right: 0;
		padding: 0 10px;
	}
</style>